package org.jetnuke.common;

import javax.servlet.http.HttpServletRequest;

import org.jetnuke.servlets.utilities.StringUtils;


public class FckEditor {
	boolean isCompatible;
	String ctx=null;
	public FckEditor(HttpServletRequest req){
		isCompatible=isCompatible(req);
		String contextName = req.getContextPath();
		if ((contextName == null) || contextName.equals("")){
			ctx="/";
		}else{
			ctx=contextName+"/";
		}
	}
	public String get(String instanceName, String value, String width, String height){
		StringBuffer tmp=new StringBuffer(500);
		
		value=StringUtils.htmlspecialchars(value);
		
		if(isCompatible){
			String link=ctx+"fckeditor/editor/fckeditor.html?InstanceName="+instanceName+"&amp;Toolbar=JetNuke";
			tmp.append("<input type=\"hidden\" id=\""+instanceName+"\" name=\""+instanceName+"\" value=\""+value+"\" style=\"display:none\" />");
			tmp.append("<input type=\"hidden\" id=\""+instanceName+"___Config\" value=\"\" style=\"display:none\" />");
			tmp.append("<iframe id=\""+instanceName+"___Frame\" src=\""+link+"\" width=\""+width+"\" height=\""+height+"\" frameborder=\"no\" scrolling=\"no\"></iframe>");
		}
		else{
			String widthCSS=width;
			String heightCSS=height;
			if(widthCSS.indexOf("%")==-1){
				widthCSS=widthCSS+"px";
			}
			if(heightCSS.indexOf("%")==-1){
				heightCSS=heightCSS+"px";
			}
			tmp.append("<textarea name=\""+instanceName+"\" rows=\"4\" cols=\"40\" style=\"width: "+widthCSS+"; height: "+heightCSS+"\" wrap=\"virtual\">"+value+"</textarea>");
		}
		return "<div>"+tmp.toString()+"</div>";
	}
	private boolean isCompatible(HttpServletRequest req){
	
		try {
			String ua=req.getHeader("User-Agent");
			if(ua==null)
				return false;
			int index=-1;
			if((index=ua.indexOf("MSIE"))!=-1 && ua.indexOf("mac")==-1 && ua.indexOf("Opera")==-1){
				
				String tmp=ua.substring(index+5,index+8).replaceAll(",",".");
				double d=Double.parseDouble(tmp);
				if(d>=5.5){
					return true;
				}
				
			}else if ((index=ua.indexOf("Gecko"))>-1){
				index=ua.indexOf("Gecko/");
				String tmp=ua.substring(index+6,index+14);
				long lg=Long.parseLong(tmp);
				if(lg>=20030210){
					return true;
				}
			}
		} catch (Throwable e) {
		}
		return false;
	}
}
